package com.jiuyin.dianjing.ui.activity.community;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.FileUtils;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.picker.SinglePicker;
import cn.bingoogolapple.photopicker.util.BGAPhotoHelper;
import cn.bingoogolapple.photopicker.util.BGAPhotoPickerUtil;
import me.jessyan.autosize.utils.LogUtils;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_CIRCLE_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_INTRO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LIST_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_UNIVERSITY_COLLEGE_NAME;
import static com.jiuyin.dianjing.constant.AppConstant.FOLDER_NAME;

public class CollegeApplyActivity extends BaseActivity {
    private static final int REQUEST_CODE_PERMISSION_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PERMISSION_TAKE_PHOTO = 2;

    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_TAKE_PHOTO = 2;
    private static final int REQUEST_CODE_CROP = 3;
    private static final int REQUEST_CODE_COLLEGE_CHOOSE_PHOTO = 4;
    private static final int REQUEST_CODE_COLLEGE_CROP = 5;
    private static final int REQUEST_SIGN = 88;
    @BindView(R.id.layout_badge)
    View layoutBadge;
    @BindView(R.id.iv_badge)
    ImageView ivBadge;
    @BindView(R.id.layout_college_theme)
    View lyCollegeTheme;
    @BindView(R.id.iv_college_badge)
    ImageView ivCollegeBadge;
    @BindView(R.id.tv_name_right)
    TextView tvName;
    @BindView(R.id.tv_intro_right)
    TextView tvIntro;
    @BindView(R.id.tv_username)
    TextView tvUserName;
    @BindView(R.id.tv_contract_right)
    TextView tvContract;
    @BindView(R.id.bt_submit)
    Button btSubmit;
    private BGAPhotoHelper mPhotoHelper;
    private ArrayList<String> universityNameList = new ArrayList<>();
    private String path = "";
    private String path1 = "";
    private String headPortrait = "";
    private String theme = "";

    @Override
    protected int setLayoutId() {
        return R.layout.activity_college_apply;
    }

    @Override
    protected void initData() {
        getUniversityNameList();
    }

    @Override
    protected void initView() {
        setTitle("申请高校");
        layoutBadge.setOnClickListener(v -> {
            choosePhoto(REQUEST_CODE_CHOOSE_PHOTO);
        });
        lyCollegeTheme.setOnClickListener(v -> {
            choosePhoto(REQUEST_CODE_COLLEGE_CHOOSE_PHOTO);
        });
        tvUserName.setText(HelperApplication.getNickName());
        tvContract.setText(HelperApplication.getMobile());

        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
        mPhotoHelper = new BGAPhotoHelper(takePhotoDir);
    }

    private void getUniversityNameList() {
        ApiResultCallback apiRequestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                if (null != data && data.has("universityNameList")) {
                    JsonArray jsonArray = data.getAsJsonArray("universityNameList");
                    if (jsonArray.size() != 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            String uName = jsonArray.get(i).getAsString();
                            universityNameList.add(uName);
                        }
                    }
                }
            }
        };
        ServerApi.post(ApiEnum.GET_UNIVERSITY_NAME_LIST, null, null, progress, null, apiRequestCallback);
    }

    @OnClick({R.id.tv_name_right, R.id.tv_intro_right, R.id.bt_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_name_right:
                if (null != universityNameList && universityNameList.size() > 0) {
                    selectUniversity();
                }
                break;
            case R.id.tv_intro_right:
                Intent intent = new Intent(this, IntroductionEsportsClubActivity.class);
                intent.putExtra("sign", tvIntro.getText().toString());
                startActivityForResult(intent, REQUEST_SIGN);
                break;
            case R.id.bt_submit:
                doPost();
                break;

        }
    }

    private void selectUniversity() {
        SinglePicker<String> picker = new SinglePicker<>(this, universityNameList);
        picker.setCanLoop(false);
        picker.setLineVisible(true);
        picker.setTextSize(18);
        picker.setSelectedIndex(0);
        picker.setGravity(Gravity.BOTTOM);
        picker.setOuterLabelEnable(true);
        picker.setSelectedTextColor(Color.GREEN);//前四位值是透明度
        picker.setUnSelectedTextColor(Color.BLACK);
        picker.setOnSingleWheelListener((index, item) -> {
        });
        picker.setOnItemPickListener((index, item) -> {
            tvName.setText(universityNameList.get(index));
        });
        picker.show();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        BGAPhotoHelper.onSaveInstanceState(mPhotoHelper, outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        BGAPhotoHelper.onRestoreInstanceState(mPhotoHelper, savedInstanceState);
    }


    void doPost() {
        if (TextUtils.isEmpty(headPortrait)) {
            ToastUtil.showShort(R.string.please_select_avatar);
            return;
        }
        if (TextUtils.isEmpty(theme)) {
            ToastUtil.showShort(R.string.please_select_theme);
            return;
        }
        if (TextUtils.isEmpty(tvName.getText())) {
            ToastUtil.showShort(R.string.please_choose_university);
            return;
        }
        if (TextUtils.isEmpty(tvIntro.getText())) {
            ToastUtil.showShort(R.string.please_edit_the_introduction_of_club);
            return;
        }
        HashMap<String, Object> data = new HashMap<>();
        data.put(KEY_TOKEN, HelperApplication.getToken());
        data.put(KEY_UNIVERSITY_COLLEGE_NAME, tvName.getText());
        data.put(KEY_CIRCLE_LOGO, "http://jiuyinesports.com/" + headPortrait);
        data.put(KEY_LIST_LOGO, "http://jiuyinesports.com/" + theme);
        data.put(KEY_INTRO, tvIntro.getText());
        JSONObject jsonObject = new JSONObject(data);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                btSubmit.setEnabled(true);
                ToastUtil.showShort(R.string.club_successfully);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                ToastUtil.showShort(msg);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
            }
        };
        ServerApi.post(ApiEnum.APPLY_FOR_CREATE_UNIVERSITY, jsonObject, null, progress, d -> addDisposable(d), requestCallback);
    }

    public void choosePhoto(int type) {
        startActivityForResult(mPhotoHelper.getChooseSystemGalleryIntent(), type);
    }

    public void takePhoto() {
        try {
            startActivityForResult(mPhotoHelper.getTakePhotoIntent(), REQUEST_CODE_TAKE_PHOTO);
        } catch (Exception e) {
            BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_take_photo);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        startPhotoZoom(uri, REQUEST_CODE_CHOOSE_PHOTO);
                    }
                }
            } else if (requestCode == REQUEST_CODE_CROP) {
//                BGAImage.display(ivBadge, R.mipmap.bga_pp_ic_holder_light, mPhotoHelper.getCropFilePath(), BGABaseAdapterUtil.dp2px(43.3f));
                if (path != null && path.length() != 0) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    //给头像设置图片源
                    //上传头像
                    ivBadge.setImageBitmap(bitmap);
                    OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                            temp.header = "http://jiuyinesports.com/" + request.getObjectKey();
                            headPortrait = request.getObjectKey();
                            Log.d("onValidationSucceeded", "headPortrait: " + headPortrait);

                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                            ToastUtil.showShort(clientException.getMessage());
                        }
                    };
                    String fileName = FileUtils.generateFileName(path);
                    HelperApplication.ossService.asyncPutImage(FOLDER_NAME + fileName, path, userCallback, null);
                }
            } else if (requestCode == REQUEST_CODE_COLLEGE_CHOOSE_PHOTO) {
                if (data != null) {
                    Uri uri = data.getData();
                    if (uri != null) {
                        startPhotoZoom(uri, REQUEST_CODE_COLLEGE_CHOOSE_PHOTO);
                    }
                }
            } else if (requestCode == REQUEST_CODE_COLLEGE_CROP) {
                if (path1 != null && path1.length() != 0) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path1);
                    //给头像设置图片源
                    //上传头像
                    ivCollegeBadge.setImageBitmap(bitmap);
                    OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                            temp.header = "http://jiuyinesports.com/" + request.getObjectKey();
                            theme = request.getObjectKey();
                            Log.d("onValidationSucceeded", "theme: " + theme);
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                            ToastUtil.showShort(clientException.getMessage());
                        }
                    };
                    String fileName = FileUtils.generateFileName(path1);
                    HelperApplication.ossService.asyncPutImage(FOLDER_NAME + fileName, path1, userCallback, null);
                }
            } else if (requestCode == REQUEST_SIGN) {
                if (data == null) {
                    return;
                }
                String intro = data.getStringExtra("intro");
                tvIntro.setText(intro);
            }
        } else {
            if (requestCode == REQUEST_CODE_CROP) {
                mPhotoHelper.deleteCameraFile();
                mPhotoHelper.deleteCropFile();
            }
        }
    }

    private void startPhotoZoom(Uri uri, int type) {
        try {
            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String address = sDateFormat.format(new Date());
            if (!FileUtils.isFileExist("")) {
                FileUtils.createSDDir("");
            }

            Uri imageUri = Uri.parse("file:///sdcard/formats/" + address + ".JPEG");
            final Intent intent = new Intent("com.android.camera.action.CROP");

            // 照片URL地址
            intent.setDataAndType(uri, "image/*");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("crop", "true");
            // 输出路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            // 输出格式
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            // 不启用人脸识别
            intent.putExtra("noFaceDetection", false);
            intent.putExtra("return-data", false);
            intent.putExtra("fileurl", FileUtils.SDPATH + address + ".JPEG");
            if (type == REQUEST_CODE_CHOOSE_PHOTO) {
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("outputX", 480);
                intent.putExtra("outputY", 480);
                path = FileUtils.SDPATH + address + ".JPEG";
                startActivityForResult(intent, REQUEST_CODE_CROP);
            } else if (type == REQUEST_CODE_COLLEGE_CHOOSE_PHOTO) {
                intent.putExtra("aspectX", 600);
                intent.putExtra("aspectY", 300);
                intent.putExtra("outputX", 600);
                intent.putExtra("outputY", 300);
                path1 = FileUtils.SDPATH + address + ".JPEG";
                startActivityForResult(intent, REQUEST_CODE_COLLEGE_CROP);
            }

        } catch (IOException e) {
            LogUtils.w(e.getMessage());
        }
    }
}
